<template>
  <div>
    <!-- 参数表单 -->
    <div class="params-form">
      <el-form :inline="true" label-width="120px">
        <el-form-item label="流域面积 (F)">
          <el-input-number v-model="designParams.F" :step="0.1" ></el-input-number>
        </el-form-item>
        <el-form-item label="洪水胖瘦系数 (w)">
          <el-input-number v-model="w" :min="0.1" :max="0.6" step="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="可变系数 (K)">
          <el-input-number v-model="K" :min="0.03" :max="0.04" step="0.001"></el-input-number>
        </el-form-item>
        <el-form-item label="选择频率">
          <el-select v-model="selectedFrequency" placeholder="请选择频率">
            <el-option label="全部显示" value="all"></el-option>
            <el-option
              v-for="item in flowResultData"
              :key="item.frequency"
              :label="`${item.frequency} %`"
              :value="item.frequency"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="recalculate">重新计算</el-button>
    </div>

    <!-- 设计洪水成果表 -->
    <el-table :data="resultsTable" style="width: 100%" border>
      <el-table-column prop="frequency" label="频率 (%)" width="120"></el-table-column>
      <el-table-column prop="QMax" label="Qm (m³/s)" width="150"></el-table-column>
      <el-table-column prop="tau" label="τ (h)" width="150"></el-table-column>
      <el-table-column prop="psi" label="ψ" width="100"></el-table-column>
      <el-table-column prop="n" label="n" width="100"></el-table-column>
    </el-table>

    <!-- 流量过程线 -->
    <div id="chartContainer" style="width: 100%; height: 400px; margin-top: 20px;"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import * as echarts from "echarts";

// 接收父组件传来的数据
const props = defineProps({
  resultsData: {
    type: Object,
    required: true,
  },
});

// 提取设计参数和初始数据
const designParams = reactive({
  F: parseFloat(props.resultsData.designParams["流域面积F"]),
});
const flowResultData = reactive([...props.resultsData.flowResultData]);

// 可调整参数
const K = ref(0.035); // 可变系数
const w = ref(0.42); // 洪水胖瘦系数

// 当前选择的频率
const selectedFrequency = ref("all"); // 默认选择 "全部显示"

// 表格数据和图表数据
const resultsTable = reactive([]);
let chartInstance = null; // 图表实例

// YDatas 和 XDatas (模拟数据)
const YDatas = [0, 10, 20, 40, 60, 80, 90, 100, 90, 80, 60, 40, 20, 10, 0];
const WDatas = [0.25, 0.30, 0.36, 0.41, 0.42, 0.48, 0.52];
const XDatas = [
  [0, 0, 0, 0, 0, 0, 0],
  [0.5, 4.5, 5.5, 3.5, 1.5, 4, 4],
  [1, 7.5, 9.5, 6.9, 5, 7, 9],
  [2, 9.5, 12, 9.7, 8, 12.5, 14],
  [2.5, 11, 13, 10.5, 9.5, 16, 18],
  [3.5, 12.2, 14.5, 12.2, 14, 19, 22.5],
  [4.5, 13, 15, 14, 16.5, 22.5, 24.5],
  [6.5, 14.5, 17.5, 21.3, 22, 25.5, 29],
  [9.5, 19, 25.5, 31.3, 29.5, 37, 40],
  [11, 21, 28, 36, 33, 42, 47],
  [16.5, 26, 34, 43.6, 41.5, 56.5, 60.5],
  [23, 37, 44.5, 51.4, 50, 64, 74.5],
  [37, 58, 60, 62.5, 63.5, 81.5, 87],
  [49, 75, 83, 76.1, 86.5, 91, 93],
  [100, 100, 100, 100, 100, 100, 100],
];

// 计算 QMax
const calculateQMax = (F, R, alpha, K) => alpha * K * R * Math.pow(F, 0.75);

// 计算 T
const calculateT = (F, R, w, QMax, dbPer = 1) => (0.278 * F * R) / (w * QMax) * dbPer;

// 计算 TDatas 和 QDatas
const calculateData = (F, R, w, QMax) => {
  const nCount = YDatas.length;
  const TDatas = new Array(nCount).fill(0);
  const QDatas = new Array(nCount).fill(0);

  let WPos = WDatas.findIndex((v) => w <= v);
  if (WPos === -1) WPos = WDatas.length - 1;

  for (let i = 0; i < nCount; i++) {
    const dbPer = XDatas[i][WPos];
    TDatas[i] = calculateT(F, R, w, QMax, dbPer) / 100;
    QDatas[i] = (YDatas[i] * QMax) / 100.0;
  }

  return { TDatas, QDatas };
};

// 针对单一频率重新计算表格和图表
const recalculateSingle = (frequency) => {
  const row = flowResultData.find((item) => item.frequency === frequency);
  if (!row) return;

  const series = [];
  const F = designParams.F;
  const R = parseFloat(row.r);
  const alpha = parseFloat(row.alpha);

  const QMax = calculateQMax(F, R, alpha, K.value);
  const T = calculateT(F, R, w.value, QMax);

  // 更新表格
  resultsTable.length = 0;
  resultsTable.push({
    frequency: row.frequency,
    QMax: QMax.toFixed(2),
    tau: T.toFixed(2),
    psi: row.psi,
    n: 0.75, // 固定值
  });

  // 更新图表
  const { TDatas, QDatas } = calculateData(F, R, w.value, QMax);
  series.push({
    name: row.frequency,
    type: "line",
    smooth: true,
    data: TDatas.map((t, i) => [t.toFixed(2), QDatas[i]]),
  });

  drawChart(series, true);
};

// 重新计算所有频率的数据
const recalculate = () => {
  resultsTable.length = 0; // 清空表格数据
  const series = [];

  flowResultData.forEach((row) => {
    const F = designParams.F;
    const R = parseFloat(row.r);
    const alpha = parseFloat(row.alpha);

    const QMax = calculateQMax(F, R, alpha, K.value);
    const T = calculateT(F, R, w.value, QMax);

    // 更新表格
    resultsTable.push({
      frequency: row.frequency,
      QMax: QMax.toFixed(2),
      tau: T.toFixed(2),
      psi: row.psi,
      n: 0.75, // 固定值
    });

    // 计算图表数据
    const { TDatas, QDatas } = calculateData(F, R, w.value, QMax);
    series.push({
      name: row.frequency,
      type: "line",
      smooth: true,
      data: TDatas.map((t, i) => [t.toFixed(2), QDatas[i]]),
    });
  });

  drawChart(series, false);
};

// 绘制图表
const drawChart = (series, showXAxisLabel) => {
  nextTick(() => {
    const chartDom = document.getElementById("chartContainer");
    if (!chartDom) return;

    if (chartInstance) chartInstance.dispose();
    chartInstance = echarts.init(chartDom);

    chartInstance.setOption({
      title: { text: "流量过程线", left: "center" },
      tooltip: { trigger: "axis" },
      legend: { bottom: 10 },
      xAxis: {
        type: "value",
        name: "时间 (h)",
        axisLabel: { show: showXAxisLabel },
      },
      yAxis: { type: "value", name: "流量 (m³/s)" },
      series,
    });
  });
};

// 初始化
onMounted(() => recalculate());

// 监听频率切换
watch(selectedFrequency, (newFrequency) => {
  if (newFrequency === "all") {
    recalculate();
  } else {
    recalculateSingle(newFrequency);
  }
});

// 销毁图表实例
onBeforeUnmount(() => {
  if (chartInstance) chartInstance.dispose();
});
</script>

<style scoped>
.params-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
</style>
